package org.lilred.nzbberry.ui;

import java.util.Timer;
import java.util.TimerTask;

import org.lilred.nzbberry.config.Resizer;
import org.lilred.nzbberry.util.FontFactory;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class FooterField extends Field {

	String text;
	int position = 0;
	int advance = 0;
	int textAnimationStartPos = 0;
	int textAnimationEndPos = 0;
	public static final int dx = Resizer.resize(5);
	public static final int period = 125;
	Timer timer = new Timer();
	
	TimerTask updatePositionTask = new TimerTask() {
		public void run() {
			//Debug statements, we'll get spammed if this is running when it shouldn't be
			System.out.println("Start: 		" + textAnimationStartPos);
			System.out.println("Current:	" + position);
			System.out.println("End:		" + textAnimationEndPos);

			//End immediately if there is no movement
			if (textAnimationStartPos == textAnimationEndPos || !isVisible()) {
				cancel();
				return;
			}
			//Move the text a little bit to the right
			position -= dx;
			invalidate();
			if (position < textAnimationEndPos) {
				cancel();
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					System.out.println(e.toString());
				}
			}
		}
	};
	
	public FooterField() {
		setFont(FontFactory.getFont(Resizer.resize(15)));
		this.text = "";
		advance = getFont().getAdvance(text);
		timer.schedule(updatePositionTask, 4000, period);
	}
	
	public FooterField(String text) {
		setFont(FontFactory.getFont(Resizer.resize(15)));
		this.text = text;
		timer.schedule(updatePositionTask, 4000, period);
	}
	
	public void updateFooter(String text) {
		this.text = text;
		this.position = 0;
		invalidate();
	}
	
	private void makeCalculations() {
		advance = getFont().getAdvance(text);
		textAnimationStartPos = (advance > getWidth()) ? 0 : getWidth() - advance;
		textAnimationEndPos = getWidth() - advance;
	}
	
	protected void layout(int width, int height) {
		setExtent(width, height);
	}

	protected void paint(Graphics g) {
		makeCalculations();
		g.setColor(0xFFFFFF);
		g.drawText(text, textAnimationStartPos + position, Resizer.resize(8));
	}

}
